package com.guigu.dh.api.service.impl;

import com.guigu.dh.api.service.ApiScheduleService;
import com.guigu.dh.common.result.Result;
import com.guigu.dh.pojo.hosp.Schedule;
import com.guigu.dh.repository.ScheduleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class ApiScheduleServiceImpl implements ApiScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    // 添加的方法
    @Override
    public Result saveSchedule(Schedule schedule) {
        // 先根据科室编号查询是否存在
        Schedule byDepcode = scheduleRepository.getScheduleByDepcodeAndHosScheduleId
                (schedule.getDepcode(),schedule.getHosScheduleId());
        if (byDepcode == null) {
            schedule.setCreateTime(new Date());
        }
        schedule.setIsDeleted(0);
        schedule.setUpdateTime(new Date());
        schedule.setStatus(1);
        Schedule save = scheduleRepository.save(schedule);
        if (save != null) {
            return Result.ok(save);
        }
        return Result.fail();
    }

    // 分页的方法
    @Override
    public Result pagingSchedule(Map<String, String> map) {
        // 取出分页条件
        String currentPage = map.get("currentPage");
        String limit = map.get("limit");
        PageRequest pageable = PageRequest.of(Integer.parseInt(currentPage)-1, Integer.parseInt(limit));
        Page<Schedule> all = scheduleRepository.findAll(pageable);
        return Result.ok(all);
    }

    // 删除的方法
    @Override
    public Result doDel(String depcode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByDepcodeAndHosScheduleId(depcode,
                hosScheduleId);
        scheduleRepository.deleteById(schedule.getId());
        return Result.ok();
    }
}
